package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyComment;
import cn.wolfcode.trip.base.domain.Tag;
import cn.wolfcode.trip.base.mapper.StrategyCommentMapper;
import cn.wolfcode.trip.base.mapper.TagMapper;
import cn.wolfcode.trip.base.query.StrategyCommentQueryObject;
import cn.wolfcode.trip.base.service.IStrategyCommentService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentMapper strategyCommentMapper;
    @Autowired
    private TagMapper tagMapper;

    @Override
    public PageInfo query(StrategyCommentQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<StrategyComment> list = strategyCommentMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void save(StrategyComment strategyComment,String[] tags) {
        //设置评论人
        strategyComment.setUser(UserContext.getCurrentUser());
        strategyCommentMapper.insert(strategyComment);

        //保存标签
        for (String tagName : tags) {

            Tag tag = tagMapper.selectByName(tagName);

            if (tag == null) {
                tag=new Tag();
                tag.setName(tagName);
                tagMapper.insert(tag);
            }

            //关联中间表
            strategyCommentMapper.inserRelation(strategyComment.getId(),tag.getId());
        }
    }

    /**
     * 根据评论id获取评论评论信息以及评论的用户信息和对应的评论攻略信息
     * @param id
     * @return
     */
    @Override
    public StrategyComment get(Long id) {
        return strategyCommentMapper.selectByPrimaryKey(id);
    }

    /**
     * 获取单个用户所有的攻略一级评论,不进行高查分页
     * @param qo
     * @return
     */
    @Override
    public PageInfo queryCommentsByUserId(StrategyCommentQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List list = strategyCommentMapper.selectForListByUserId(qo);
        return new PageInfo(list);
    }
}
